// waveeditorDoc.cpp : implementation of the CWaveeditorDoc class
//

#include "stdafx.h"
#include "waveeditor.h"
#include "MainFrm.h"
#include "waveeditorDoc.h"
#include "myStatusBar.h"
#include "WaveeditorDialogs.h"
#include <map>
#include <vector>
#include "MyGraphFrame.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

////////////////////////////////////////////////////
//Static functions

static long GetPositionOfSignalByNameAndType( const CString Name, 
											  const long Type, 
											  const CArray< Signal, Signal > &Signals )
{
	long Result = -1;
	long NumberOfElements = Signals.GetSize();
	for ( int i = 0; i < NumberOfElements; i++ )
	{
		if ( Signals[i].Name == Name && Signals[i].SignalType == Type )
		{
			Result = i;
			break;
		}
	}
	return Result;
}

static void AddBraces( Signal &Object )
{
	switch ( Object.SignalType )
	{
	case SIGNAL_WITH_SQUARE_BRACKETS:
		{
			Object.Name = '[' + Object.Name + ']';
			break;
		}
	case SIGNAL_WITH_TRIANGULAR_BRACKETS:
		{
			Object.Name = '<' + Object.Name + '>';
			break;
		}
	}
}

static void AddIndex( Signal &Object, 
					  int &Index, 
					  const std::map< CString, std::vector<long> > &NamesAndPositions )
{
	CString CurrentName;
	while ( true )
	{
		CurrentName = Object.Name + "_" + Long64ToCString( Index );
		if ( NamesAndPositions.find( CurrentName ) != NamesAndPositions.end() )
		{
			Index++;
			continue;
		}
		else
		{
			Object.Name = CurrentName;
			break;
		}
	}
}

static void GetIdenticalNames( const CArray< Signal, Signal > &Signals, 
							   std::map< CString, std::vector<long> > &NamesAndPositions )
{
	using std::map;
	using std::vector;
	using std::pair;
	int NumberOfSignals = Signals.GetCount();
	for ( int i = 0; i < NumberOfSignals; i++ )
	{
		NamesAndPositions.insert( pair<CString, vector<long> >( Signals[i].Name, vector<long>() ) ).
			         first->second.push_back( i );
	}
}

static void AddBracesToIdenticalSignals( CArray< Signal, Signal > &Signals, 
							       const std::map< CString, std::vector<long> > &NamesAndPositions )
{
	using std::map;
	using std::vector;
	for ( map< CString, vector<long> >::const_iterator i = NamesAndPositions.begin();
		  i != NamesAndPositions.end(); 
		  i++ )
	{
		unsigned int Size = i->second.size();
		if ( Size > 1 )
		{
			for ( unsigned int k = 0; k < Size; k++ )
			{
				AddBraces( Signals[(i->second)[k]] );
			}
		}
	}
}

static void AddIndexesToIdenticalSignals( CArray< Signal, Signal > &Signals, 
							       const std::map< CString, std::vector<long> > &NamesAndPositions )
{
	using std::map;
	using std::vector;
	for ( map< CString, vector<long> >::const_iterator i = NamesAndPositions.begin(); 
		  i != NamesAndPositions.end(); 
		  i++ )
	{
		int Size = i->second.size();
		if ( Size > 1 )
		{
			for ( int k = 0, Index = 0; k < Size; k++, Index++ )
			{
				AddIndex( Signals[(i->second)[k]], Index, NamesAndPositions );
			}
		}
	}
}

static void HandleIdenticalNames( CArray< Signal, Signal > &Signals )
{
	using std::map;
	using std::vector;
	
	map< CString, vector<long> > NamesAndPositions;

	GetIdenticalNames( Signals, NamesAndPositions );
	AddBracesToIdenticalSignals( Signals, NamesAndPositions );

	NamesAndPositions.clear();
	
	GetIdenticalNames( Signals, NamesAndPositions );
	AddIndexesToIdenticalSignals( Signals, NamesAndPositions );
}

/////////////////////////////////////////////////////////////////////////////
// CWaveeditorDoc
IMPLEMENT_DYNCREATE(ZWaveeditorDoc, CDocument)

BEGIN_MESSAGE_MAP(ZWaveeditorDoc, CDocument)
	//{{AFX_MSG_MAP(ZWaveeditorDoc)
	//ON_COMMAND(ID_LOAD_SIGNALS, OnLoadSignals)
	ON_COMMAND(ID_DOCUMENTPROPERTIES, OnDocumentproperties)
	ON_COMMAND(ID_FILE_SAVE			, OnFileSave)
	ON_COMMAND(ID_FILE_SAVE_AS		, OnFileSaveAs)
	//}}AFX_MSG_MAP
	ON_COMMAND(ID_ALWAYS_SHOW_HINT, OnAlwaysShowHint)
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CWaveeditorDoc construction/destruction

ZWaveeditorDoc::ZWaveeditorDoc()://_globalsignals(&StatusList),
GroupName(_T(""))
{
	// TODO: add one-time construction code here
	treewaschanged				=	TRUE;
	bEnableGraphViewAlwaysShowHint	=	FALSE;
	EditWindowOpened			=	FALSE;
	GraphWindowOpened			=	FALSE;
	compressionstep				=	STEPB;
	efectiveedge				=	1;
	twopath						=	BST_UNCHECKED;
	version						=	VERSION_3;
	compression_step_string[0]	=	" -stepB ";
	compression_step_string[1]	=	" -stepA ";
	phase_drive_tree_name		=	"Special Specification";
	phase_drive_names[0]		=	"ADCLK" ; 
	phase_drive_names[1]		=	"DS1"; 
	phase_drive_names[2]		=	"DS2"; 
	phase_drive_names[3]		=	"R"; 
	phase_drive_names[4]		=	"H1"; 
	phase_drive_names[5]		=	"H2"; 
	phase_drive_names[6]		=	"H3"; 
	phase_drive_names[7]		=	"H4";
	phase_drive_names[8]		=	"UTG_CCLK";
	doc_fileheader.number_of_signals	=	NUMBEROFPHASEDRIVE;
	doc_fileheader.global_phase			=	0;
	for(int i=0;i<doc_fileheader.number_of_signals;i++)
	{
		doc_fileheader.fall [i]	=	0;
		doc_fileheader.rise [i]	=	0;
		doc_fileheader.drive[i]	=	0;
	}
	graphNormalCursor	=	((ZWaveeditorApp*)AfxGetApp())->LoadCursor(IDC_GRAPHCURSOR);
	graphZoomCursor		=	((ZWaveeditorApp*)AfxGetApp())->LoadCursor(IDC_ZOOMCURSOR);
	graphScrollCursor	=	((ZWaveeditorApp*)AfxGetApp())->LoadCursor(IDC_SCROLLCURSOR);
	graphScrollCursorPush = ((ZWaveeditorApp*)AfxGetApp())->LoadCursor(IDC_SCROLLCURSORPUSH);

	UpdateAllViews(0);
}

ZWaveeditorDoc::~ZWaveeditorDoc()
{
	for( int i = 0; i < _script.GetCount(); i++ )
	{
		delete _script[i];
	}
	_script.RemoveAll();
	StatusList.ClearLog();
	templist.ClearLog();

}

BOOL ZWaveeditorDoc::OnNewDocument()
{
	if (!CDocument::OnNewDocument())
		return FALSE;

	// TODO: add reinitialization code here
	// (SDI documents will reuse this document)
	return TRUE;
}



/////////////////////////////////////////////////////////////////////////////
// CWaveeditorDoc serialization


void ZWaveeditorDoc::Serialize(CArchive& ar)
{
	StatusList.ClearLog();
    if (ar.IsStoring())
	{
		// TODO: add loading code here
		ar<<version;
		ar<<compressionstep;
		ar<<efectiveedge;
		ar<<twopath;
		if(_script.GetSize() >0)
		{
			ar<<_script.GetSize();
			for(int i=0;i<_script.GetSize();i++)
			{
				_script[i]->Serialize( ar );
			}
			StatusList.AddMessage("Document was saved");
			UpdateAllViews(0);
			BinFileHeaderSerialize(ar);
			return;
		}
		int size	=	0;
		ar<<size;
		//_globalsignals.Serialize(ar);
		BinFileHeaderSerialize(ar);
		StatusList.AddMessage("WARNING:Document was saved empty");
		UpdateAllViews(0);
	}
	else
	{
		// TODO: add storing code here
		ar>>version;
		ar>>compressionstep;
		ar>>efectiveedge;
		ar>>twopath;
		int size;
		ar>>size;
		for(int i=0;i<size;i++)
		{
			LoadScriptOrLogFromSOW( ar );
		}
		UpdateAllViews(0);
		version	=	VERSION_3;
		return;
		UpdateAllViews(0);
	}
}


/////////////////////////////////////////////////////////////////////////////
// CWaveeditorDoc diagnostics

#ifdef _DEBUG
void ZWaveeditorDoc::AssertValid() const
{
	CDocument::AssertValid();
}

void ZWaveeditorDoc::Dump(CDumpContext& dc) const
{
	CDocument::Dump(dc);
}
#endif //_DEBUG

/////////////////////////////////////////////////////////////////////////////
// CWaveeditorDoc commands

void ZWaveeditorDoc::OnAddScriptOrLog() 
{
	// TODO: Add your command handler code here
	if((CheckIfEditWindowOpened() == TRUE)||(CheckIfGraphWindowOpened() == TRUE))
	{
		AfxMessageBox("Please Close All Graph and Editing Windows");
		return;
	}
	StatusList.ClearLog();
	ZWaveeditorApp	*pWinapp	=	(ZWaveeditorApp*) AfxGetApp();
	CString scriptdir			=	pWinapp->ScriptDirectory;
	scriptdir					+=	"\\*.srp;*.log;*.txt";
	CString Filters= (CString)"Data Files (*.srp;*.log;*.txt)|*.srp;*.log;*.txt|"+
						  	  "Script Files (*.srp)|*.srp|"+
							  "Log Files (*.log)|*.log|"+
							  "Text Log Files(*.txt)|*.txt|"+
							  "All Files (*.*)|*.*||";
	CFileDialog FileDialog(TRUE,"srp",scriptdir,	OFN_FILEMUSTEXIST	| 
											OFN_HIDEREADONLY	|
											OFN_ALLOWMULTISELECT , Filters);
	if (FileDialog.DoModal() == IDOK)	
	{
		POSITION pos	=FileDialog.GetStartPosition();
		if(pos == NULL)
		{
			return;
		}
		while(pos != NULL)
		{
			CString  FileName	= FileDialog.GetNextPathName( pos );
			LoadScriptOrLogFromSRP( FileName );
		}
		UpdateAllViews(0);
	}
	
}

void ZWaveeditorDoc::LoadScriptOrLogFromSRP( CString FileName )
{
	if((CheckIfEditWindowOpened() == FALSE)&&(CheckIfGraphWindowOpened() == FALSE))
	{
		bool LoadSuccess = true;
		CString FileExtension = GetFileExtension( FileName );
		scenario	*newscenario	=	new scenario(&StatusList, FileName);
		if ( FileExtension.Compare( "srp" ) == 0 )
		{
			newscenario->LoadGlobalSignalListFromScriptFile( FileName );
			if ( LoadScriptFile( FileName, newscenario ) == false )
			{
				LoadSuccess = false;
				delete newscenario;
			}
		}
		else if (( FileExtension.Compare( "log" ) == 0 ) || ( FileExtension.Compare( "txt" ) == 0 ))
		{
			CArray< Signal, Signal > Signals;
			unsigned __int64 TotalSize = 0;
			if ( !GetValuesFromLogFile( FileName, &Signals, TotalSize, newscenario->LogReadType ) )
			{
				LoadSuccess = false;
				delete newscenario;
			}
			else
			{
				ConvertOldSignalValuesToScriptCompatible( Signals );
				newscenario->LoadGlobalSignalListFromArray( Signals );
				newscenario->LoadSignalsFromArray( Signals, TotalSize );
			}
		}
		else
		{
			StatusList.AddMessage("ERROR:Unknown File format");
			delete newscenario;
			LoadSuccess = false;
		}

		if ( LoadSuccess == true )
		{
			newscenario->CutReturnFreeSpace();
			_script.Add(newscenario);
			selectedscenario = _script.GetUpperBound();
			treewaschanged	=	TRUE;
			StatusList.AddMessage("Loading file : '"+FileName+"'  Succeded");
		}
		else
		{
			StatusList.AddMessage("ERROR: Loading file : '"+FileName+"'  FAILED");
		}
	}
	else
	{
		AfxMessageBox("Please Close All Graph and Editing Windows");
	}
}

void ZWaveeditorDoc::LoadScriptOrLogFromSOW( CArchive& ar )
{
	if ( (CheckIfEditWindowOpened() == FALSE)&&(CheckIfGraphWindowOpened() == FALSE) )
	{
		bool LoadSuccess = true;
		scenario	*newscenario	=	new scenario( &StatusList, "" );
		newscenario->Serialize( ar );
		CString FileExtension = GetFileExtension( newscenario->filename );
		
		if ( FileExtension.Compare( "srp" ) == 0 )
		{
			if ( LoadScriptFile( newscenario->filename, newscenario ) == false )
			{
				delete newscenario;
				LoadSuccess = false;
			}
		}
		else if (( FileExtension.Compare( "log" ) == 0 ) || ( FileExtension.Compare( "txt" ) == 0 ))
		{
			CArray< Signal, Signal > Signals;
			unsigned __int64 TotalSize = 0;
			if ( !GetValuesFromLogFile( newscenario->filename, &Signals, TotalSize, newscenario->LogReadType ) )
			{
				delete newscenario;
				LoadSuccess = false;
			}
			ConvertOldSignalValuesToScriptCompatible( Signals );
			newscenario->LoadSignalsFromArray( Signals, TotalSize );
		}
		else
		{
			StatusList.AddMessage("ERROR:Unknown File format");
			delete newscenario;
			LoadSuccess = false;
		}

		if ( LoadSuccess == true )
		{
			newscenario->CreateGroupOfWavesignalsForEachGroupInScenarioSignls();
			newscenario->CutReturnFreeSpace();
			_script.Add(newscenario);
			selectedscenario = _script.GetUpperBound();
			treewaschanged	=	TRUE;
			StatusList.AddMessage("Loading file : '"+newscenario->filename+"'  Succeded");
		}
	}
	else
	{
		AfxMessageBox("Please Close All Graph and Editing Windows");
	}
}

/*BOOL ZWaveeditorDoc::TryToLoadDefaultSignals()
{
	if(LoadDefaultSignals() != 0)
	{
		StatusList.AddMessage("ERROR:Cannot load script file : Signal not defined");
		StatusList.AddMessage("ERROR:Please load signals definition file");
		return FALSE;
	}
	_globalsignals.SetDefaults();
	return TRUE;
}*/
int ZWaveeditorDoc::ExportTree(CTreeCtrl *_tree,DWORD num)
{
/*	if((CheckIfEditWindowOpened() == TRUE)||(CheckIfGraphWindowOpened() == TRUE))
	{
		return -1;
	}
*/	
	ExportTreeGlobalValues(_tree,num);
	for(int i=0;i<_script.GetSize();i++)
	{
		_script[i]->ExportTree(_tree,num);
	}
	return 0;
}

int ZWaveeditorDoc::ExportTreeGlobalValues(CTreeCtrl* _tree, DWORD num)
{
	HTREEITEM	glplace	=	_tree->GetNextItem(NULL,TVGN_CHILD);
	if(glplace	==	NULL)
	{
		glplace	=	_tree->InsertItem(phase_drive_tree_name,1,1,NULL);
		_tree->SetItemData(glplace,num^10);
	}
	else
	{
		_tree->SetItemText(glplace,phase_drive_tree_name);
		_tree->SetItemData(glplace,num^10);
	}
	return 0;
}

/*void ZWaveeditorDoc::OnLoadSignals() 
{
	// TODO: Add your command handler code here
	if((CheckIfEditWindowOpened() == TRUE)||(CheckIfGraphWindowOpened() == TRUE))
	{
		AfxMessageBox("Please Close All Graph and Editing Windows");
		return;
	}
	StatusList.ClearLog();
	char Filters[]= "Signal Files (*.sig)|*.sig|All Files (*.*)|*.*||";
	CFileDialog file(TRUE,"sig","*.sig",OFN_FILEMUSTEXIST| OFN_HIDEREADONLY, Filters);
	if (file.DoModal() == IDOK)	
	{
		if(_globalsignals.LoadSignals(file.GetPathName() )!= 0)
		{
			StatusList.AddMessage("ERROR:Cannot load signal definition file"+file.GetPathName());
		}
		else
		{
			StatusList.AddMessage("signal definition file :  '"+file.GetPathName()+"'   was loaded successefully");
		}

	}
	
	UpdateAllViews(NULL);
	
}*/


bool ZWaveeditorDoc::LoadScriptFile(CString filename, scenario* newscenario)
{
	int res	=	newscenario->LoadScriptFile(filename);
	bool Result = true;
	if(res	<0)
	{
		StatusList.AddMessage("ERROR:loading script file :"+filename+"  FAILED");
		Result = false;
	}
	/*else
	{
		for(int i=0;i<_script.GetSize();i++)
		{
			if((_script[i] != NULL)&&(_script[i]->GetFileNameOnly() == newscenario->GetFileNameOnly()))
			{
				StatusList.AddMessage("ERROR: on loading  script file <"+newscenario->GetFileName() + ">");
				StatusList.AddMessage("ERROR:script file exist");
				Result = false;
			}
		}
	}*/
	return Result;
}


void ZWaveeditorDoc::UpdateScriptFromSelection(HTREEITEM pos)
{
	if((CheckIfEditWindowOpened() == TRUE)||(CheckIfGraphWindowOpened() == TRUE))
	{
		AfxMessageBox("Please Close All Graph and Editing Windows");
		return;
	}
	StatusList.ClearLog();
	for(int i=0;i<_script.GetSize();i++)
	{
		if(_script[i]->CheckIfSelectedTree(pos) == TRUE)
		{
			selectedscenario = i;
			CString filename			=	_script[i]->GetFileName();
			scenario	*selscenrio		=	_script[i];
//			_script.RemoveAt(i);
//			delete		selscenrio;
			scenario	*tempscenario;
			tempscenario				=	new scenario(&StatusList, filename);
			tempscenario->LoadGlobalSignalListFromScriptFile( filename );
			int res						=	tempscenario->LoadScriptFile( filename );
			if(res	<0)
			{
				delete tempscenario;
				StatusList.AddMessage("ERROR:updating script file :"+filename+"  FAILED");
			}
			else
			{
				StatusList.AddMessage("updating script file : '"+filename+"'  Succeded");
//				_script.Add(tempscenario);
				delete selscenrio;
				_script[i]	=	tempscenario;
				UpdateAllViews(0);
				return;
			}
		}
	}
	StatusList.AddMessage("ERROR:Not found script to update");
	UpdateAllViews(0);
}

BOOL ZWaveeditorDoc::GetValuesFromLogFile( CString filename, CArray< Signal, Signal > *Signals, unsigned __int64 &TotalSize, LogReadingType TypeOfReading  )
{
	CStdioFile LogFile;
	BOOL     LogFileOpenResult = LogFile.Open(filename, CFile::modeRead | CFile::typeText);
	if(LogFileOpenResult == FALSE)
	{
		StatusList.AddMessage("ERROR:Cannnot open log file :"+filename);
		UpdateAllViews(0);
		return FALSE;
	}
	
	HandleLines( LogFile, Signals, TotalSize, TypeOfReading );
	
	LogFile.Close();
	if ( Signals->GetSize() == 0 )
	{
		StatusList.AddMessage("ERROR:loading log file :"+filename+"  FAILED");
		UpdateAllViews(0);
		return FALSE;
	}
	return TRUE;
}

void ZWaveeditorDoc::HandleLines( CStdioFile &LogFile,
								  CArray< Signal, Signal > *Signals,
								  unsigned __int64& TotalSize,
								  LogReadingType TypeOfReading)
{	
	long LineNumber = 0;
	unsigned __int64 TemporaryTotalSize = 0;
	CString Line;
	CString ThreadName="";
	unsigned long Rollover = 0;
	unsigned __int64 LastValue = 0;

	while(LogFile.ReadString(Line))
	{
		LineMembers LineMembrs;
		LineNumber++;
		Line.Trim();
		int CommentPos = Line.Find( "//" );
		if ( CommentPos >= 0 )
		{
			Line = Line.Mid( 0, CommentPos );
		}
		int LineType = GetLineType( Line );
		switch (LineType)
		{
		case NO_BRACKETS_STRING:
		case BRACKETS_STRING:
			{
				long (LogReadingType::*TypeOfAnyLines);
				TypeOfAnyLines = (LineType == NO_BRACKETS_STRING)?	
					&LogReadingType::TypeOfNoBracketLines : &LogReadingType::TypeOfBracketLines;
				if ( TypeOfReading.*TypeOfAnyLines == NO_READ )
				{
					break;
				}
				GetValuesFromString( Line, &LineMembrs );
				if ( TypeOfReading.*TypeOfAnyLines == BY_STRING )
				{
					LineMembrs.Name += LineMembrs.Comment;
				}
				LineMembrs.Name = ThreadName + LineMembrs.Name;
				if ( LastValue > LineMembrs.TimeMark )
				{
					Rollover++;
				}
				LastValue = LineMembrs.TimeMark;
				LineMembrs.TimeMark += Rollover*MAX_TIME_VALUE_IN_LOG;
				AddNewTimingMark ( LineMembrs, Signals );
				TemporaryTotalSize = LineMembrs.TimeMark;
				break;
			}
		case INCORRECT_STRING:
			{
				StatusList.AddMessage("ERROR: Incorrect line "+ Long64ToCString(LineNumber) );
				break;
			}
		case THREAD_NAME_STRING:
			{
				Line = Line.Mid(7);
				Line.Trim();
				Line.Replace( ' ', '_' );
				ThreadName = "\"" + Line + "\"_";
				if ( TemporaryTotalSize > TotalSize )
				{
					TotalSize = TemporaryTotalSize;
				}
				TemporaryTotalSize = 0;
				Rollover = 0;
				LastValue = 0;
				break;
			}
		}
	}
	if ( TemporaryTotalSize > TotalSize )
	{
		TotalSize = TemporaryTotalSize;
	}
}

enum LineTypes ZWaveeditorDoc::GetLineType( CString Line)
{
	if ( Line.GetLength() == 0 )
	{
		return EMPTY_STRING;
	}
	Line.MakeLower();
	int Position = Line.Find("thread:", 0);
	if ( Position == 0 )
	{
		return THREAD_NAME_STRING;
	}
	Position = Line.Find(' ', 0);
	if ( Position < 8 )
	{
		return INCORRECT_STRING;
	}
	for ( int i = 0; i < Position; i++ )
	{
		if ( Line[i] < '0' || Line[i] >'9' )
		{
			return INCORRECT_STRING;
		}
	}
	Position = Line.Find(" ms - ",Position);
	if (Position == -1)
	{
		Position = Line.Find(" us - ",8);
		if (Position == -1)
		{
			return INCORRECT_STRING;
		}
	}
	Line = Line.Mid(Position + 5);
	Line.TrimLeft();
	if ( (Line[0] == '[' && (Line.Find(']') >= 0)) ||
		 (Line[0] == '<' && (Line.Find('>') >= 0)) )
	{
		return BRACKETS_STRING;
	}
	return NO_BRACKETS_STRING;
}

void ZWaveeditorDoc::GetValuesFromString( CString Line, LineMembers *LineMembrs )
{
	int Position = Line.Find(' ', 0 );

	CString SubLine = Line.Mid( 0, Position );
	LineMembrs->TimeMark = CStringToLong( SubLine );

	Line.Mid( Position );
	if ( (Position = Line.Find(" ms - ", 0)) == -1 )
	{
		Position = Line.Find(" us - ", 0);
		LineMembrs->TimeType = MICRO_SECONDS;
	}
	else
	{
		LineMembrs->TimeType = MILLI_SECONDS;
	}
	Line = Line.Mid(Position + 5);
	Line.TrimLeft();
	
	if ( Line[0] == '[' && (Position = Line.Find(']') ) >= 0 )
	{
		LineMembrs->Type = SIGNAL_WITH_SQUARE_BRACKETS;
		LineMembrs->Name = Line.Mid(1, Position - 1 );
		LineMembrs->Comment = Line.Mid( Position + 1 );
	}
	else if ( Line[0] == '<' && (Position = Line.Find('>') ) >= 0 )
	{
		LineMembrs->Type = SIGNAL_WITH_TRIANGULAR_BRACKETS;
		LineMembrs->Name = Line.Mid(1, Position - 1 );
		LineMembrs->Comment = Line.Mid( Position + 1 );
	}
	else
	{
		Position = Line.FindOneOf( " \t\r\n" );
		LineMembrs->Type = SIGNAL_WITHOUT_BRACKETS;
		if ( Position < 0 )
		{
			LineMembrs->Name = Line;
			LineMembrs->Comment = "";
		}
		else
		{
			LineMembrs->Name = Line.Mid(0, Position);
			LineMembrs->Comment = Line.Mid( Position );
		}
	}
}

void ZWaveeditorDoc::AddNewTimingMark ( LineMembers LineMembrs, CArray< Signal, Signal > *Signals )
{
	int Position = GetPositionOfSignalByNameAndType( LineMembrs.Name, LineMembrs.Type, *Signals );
	if ( -1 == Position )
	{
		Signals->Add( Signal(LineMembrs) );
	}
	else
	{
		int UpperBound = (*Signals)[Position].Changes.GetUpperBound();
		__int64 LastTimeMark = (*Signals)[Position].Changes[UpperBound];
		if ( LastTimeMark <= LineMembrs.TimeMark )
		{
			if ( LineMembrs.Type == SIGNAL_WITH_SQUARE_BRACKETS )
			{
				(*Signals)[Position].Changes.Add( LineMembrs.TimeMark );
				(*Signals)[Position].Comments.Add( LineMembrs.Comment );
			}
			else if ( LastTimeMark != LineMembrs.TimeMark )
			{
				(*Signals)[Position].Changes.Add( LineMembrs.TimeMark - 1 );
				(*Signals)[Position].Changes.Add( LineMembrs.TimeMark );
				(*Signals)[Position].Comments.Add( LineMembrs.Comment );
				(*Signals)[Position].Comments.Add( LineMembrs.Comment );
			}
			else
			{
				(*Signals)[Position].Changes.SetAt( UpperBound, LineMembrs.TimeMark - 1 );
				(*Signals)[Position].Comments.SetAt( UpperBound, LineMembrs.Comment );
			}
		}
		else
		{
			StatusList.AddMessage("ERROR: Incorrect value " +
									Long64ToCString(LineMembrs.TimeMark) +
									" in signal: \"" +
									(*Signals)[Position].Name +
									"\" after value " +
									Long64ToCString(LastTimeMark) +
									". This value is ignored.");
		}
		
	}
	
}

void ZWaveeditorDoc::ConvertOldSignalValuesToScriptCompatible( CArray< Signal, Signal > &Signals )
{
	long NumberOfSignals = Signals.GetCount();
	for ( int i = 0; i < NumberOfSignals; i++ )
	{
		Signals[i].Name.Replace( ' ', '_' );
		long UpperBoundOfChanges = Signals[i].Changes.GetUpperBound();
		for ( int j = UpperBoundOfChanges; j > 0; j-- )
		{
			Signals[i].Changes[j] -= Signals[i].Changes[j-1];
		}
	}
	HandleIdenticalNames( Signals );
}

/*int ZWaveeditorDoc::LoadDefaultSignals()
{
	if((CheckIfEditWindowOpened() == TRUE)||(CheckIfGraphWindowOpened() == TRUE))
	{
		AfxMessageBox("Please Close All Graph and Editing Windows");
		return -1;
	}
	ZWaveeditorApp	*pWinapp	=	(ZWaveeditorApp*) AfxGetApp();
	CString configdir			=	pWinapp->ConfigurationDirectory;
	configdir					+=	"\\default.sig";
	if(_globalsignals.LoadSignals(configdir)!= 0)
	{
		StatusList.AddMessage("ERROR:Cannot load signal definition file: default.sig");
		return -1;
	}
	else
	{
		StatusList.AddMessage("signal definition file :  default.sig   was loaded successefully");
		return 0;
	}

}*/

int ZWaveeditorDoc::OnSavetovectorfile(CTreeCtrl *_tree,HTREEITEM _item)
{
	if((CheckIfEditWindowOpened() == TRUE)||(CheckIfGraphWindowOpened() == TRUE))
	{
		AfxMessageBox("Please Close All Graph and Editing Windows");
		return -1;
	}
	StatusList.ClearLog();
	for(int i=0;i<_script.GetSize();i++)
	{
		if(_script[i]->CheckIfSelectedFrame(_tree,_item) == TRUE)
		{
			selectedscenario = i;
			ZWaveeditorApp*	pWinapp			=	(ZWaveeditorApp*) AfxGetApp();
			CString			vectordir		=	pWinapp->VectorsDirectory	+"\\";
			CString			outputdir		=	pWinapp->OutputDirectory	+"\\";
			CString			name			=	_tree->GetItemText(_item);
			int				posbegin		=	name.Find("<",0);
			int				posend			=	name.Find(">",0);
							name			=	name.Mid(posbegin+1,posend-posbegin-1);
			CString			vectorfilename	=	outputdir+_script[i]->GetFileNameOnly()+"_"+name+".txt";
//-------------------------------------------------------------------------------------------
			char Filters[]= "Vector Files (*.txt)|*.txt|All Files (*.*)|*.*||";
			CFileDialog file(FALSE,"txt",vectorfilename,OFN_FILEMUSTEXIST| OFN_HIDEREADONLY, Filters);
			if (file.DoModal() == IDCANCEL)	
			{
				return -1;
			}
//--------------------------------------------------------------------------------------------
			vectorfilename	=	file.GetPathName();
			int	pos			=	vectorfilename.Find(".txt",0);
			if(pos	<	0)
			{
				vectorfilename	+=".txt";
			}
			FILE	*pVfile	=	fopen((LPCSTR)vectorfilename,"w");	
			if(pVfile	==	NULL)
			{ 
				StatusList.AddMessage("ERROR:Hardware error cannont write to disk");
				UpdateAllViews(0);
				return -1;
			}
			
			_script[i]->OpendialogWritingVector();
			if(_script[i]->GenerateVectorFileFromFrame(name,pVfile) == -1)
			{
				_script[i]->ClosedialogWritingVector();
				fclose(pVfile);
				return -1;
			}
			fclose(pVfile);
			StatusList.AddMessage("vector file <"+vectorfilename+"> was generated successfuly");
			_script[i]->ClosedialogWritingVector();
			pos						=	vectorfilename.Find(".txt",0);
			CString outputfilename	=	vectorfilename;	
//			if(pos>=0)
//			{
//				outputfilename		=	vectorfilename.Mid(0,pos);
//			}
			RunCompressor(vectorfilename,outputfilename,_script[i]->GetFrameHTotal(name),_script[i]->GetFrameVTotal(name),
							_script[i]->GetFrameVTotal_2(name),_script[i]->GetFrameSubRes(name));
			UpdateAllViews(0);
			return 0;
		}
	}
	StatusList.AddMessage("ERROR:Not found frame to convert to vector file");
	UpdateAllViews(0);
	return -1;
}




int ZWaveeditorDoc::OnItemInfo(CTreeCtrl *_tree, HTREEITEM _item)
{
//	if(DocumentLocked	==	TRUE)
//	{
//		return -1;
//	}
	StatusList.ClearLog();
	for(int i=0;i<_script.GetSize();i++)
	{
		if(_script[i]->CheckIfSelectedGroup(_tree,_item) == TRUE)
		{
			selectedscenario = i;
			CString name	= _tree->GetItemText(_item);
			int posbegin	=	name.Find("<",0);
			int posend		=	name.Find(">",0);
			name			=	name.Mid(posbegin+1,posend-posbegin-1);
			_script[i]->OnItemInfo(name);
			UpdateAllViews(0);
			return 0;
		}
	}
	StatusList.AddMessage("ERROR:Not found information on selected item");
	UpdateAllViews(0);
	return -1;

}


void ZWaveeditorDoc::OnEditscriptfile(CTreeCtrl *_tree, HTREEITEM _item)
{
	last_tree			=	_tree;
	last_item			=	_item;
	StatusList.ClearLog();
	CString treename	=	_tree->GetItemText(_item);
	if(treename	==	phase_drive_tree_name)
	{
		OnEditGlobalValues(&templist);
		selectedscenario	=	-1;
		if(CheckIfEditWindowOpened() == FALSE)
		{
			ParentMainFrame	*myframe	=	(ParentMainFrame*)AfxGetMainWnd();
			editframe	=	myframe->onEditWindow();
		}
		else
		{
			editframe->DestroyWindow();
			ParentMainFrame	*myframe	=	(ParentMainFrame*)AfxGetMainWnd();
			editframe					=	myframe->onEditWindow();
		}
		CloseGraphWindow();
		SetEditWindowClosed();
		UpdateAllViews(0);
		SetEditWindowOpened();
		return;
	}
	for(int i=0;i<_script.GetSize();i++)
	{
		if(_script[i]->CheckIfSelectedGroup(_tree,_item) == TRUE)
		{
			selectedscenario = i;
			if ( GetFileExtension( _script[i]->filename ) == "log" )
			{
				StatusList.AddMessage("ERROR:You can't edit log-files");
				UpdateAllViews(0);
				return;
			}
			CString name	= _tree->GetItemText(_item);
			int posbegin	=	name.Find("<",0);
			int posend		=	name.Find(">",0);
			name			=	name.Mid(posbegin+1,posend-posbegin-1);
			if(_script[i]->OnEditscriptfile(name,&templist) >= 0)
			{
				selectedscenario		=	i;
				if(CheckIfEditWindowOpened() == FALSE)
				{
					ParentMainFrame	*myframe	=	(ParentMainFrame*)AfxGetMainWnd();
					editframe					=	myframe->onEditWindow();
				}
				else
				{
					editframe->DestroyWindow();
					ParentMainFrame	*myframe	=	(ParentMainFrame*)AfxGetMainWnd();
					editframe					=	myframe->onEditWindow();
				}
				CloseGraphWindow();
				SetEditWindowClosed();
				UpdateAllViews(0);
				SetEditWindowOpened();
			}
			else
			{
				SetEditWindowClosed();
				UpdateAllViews(0);
			}
			return;
		}
	}
	StatusList.AddMessage("ERROR:Not found information on selected item");
	UpdateAllViews(0);
	return ;
}

void ZWaveeditorDoc::CloseGraphWindow()
{
	if ( CheckIfGraphWindowOpened() == TRUE )
	{
		graphframe->DestroyWindow();
		SetGraphWindowClosed();
	}
}

CString ZWaveeditorDoc::GetPathOnly()
{
	CString _path	=	GetPathName();
	_path.MakeReverse();
	int pos	=	_path.Find("\\",0);
	if(pos <0)
	{
		return "";
	}
	_path	=	_path.Mid(pos);
	_path.MakeReverse();
	return _path;
}



void ZWaveeditorDoc::SetTitle(LPCTSTR lpszTitle) 
{
	// TODO: Add your specialized code here and/or call the base class
	CString tit	=	(CString)lpszTitle+"\0 fer"+"\0 der";
	CDocument::SetTitle(tit);//lpszTitle+"\nfer"+"\nder");
	UpdateAllViews(0);
}

void ZWaveeditorDoc::SetEditWindowOpened()
{
	EditWindowOpened	=	TRUE;
}

void ZWaveeditorDoc::SetGraphWindowOpened()
{
	GraphWindowOpened	=	TRUE;
}

void ZWaveeditorDoc::SetEditWindowClosed()
{
	EditWindowOpened	=	FALSE;
}

void ZWaveeditorDoc::SetGraphWindowClosed()
{
	GraphWindowOpened	=	FALSE;
}

CString ZWaveeditorDoc::GetGroupName() const
{
	return GroupName;
}

int ZWaveeditorDoc::OnEditscriptRun(CEdit *_edit, int SelectedScenario)
{
	StatusList.ClearLog();
	int numoflines	=	_edit->GetLineCount();
	if(numoflines <= 1)
	{
		StatusList.AddMessage("ERROR:No data to compile :: Please input legal text");
		UpdateAllViews(0);
		return -1;
	}
	templist.ClearLog();
	char	_line[250];
	for(int i=0;i<numoflines;i++)
	{
		int res	=	_edit->GetLine(i,_line,250);
		_line[res]	=	'\0';
		templist.AddMessage(_line);
	}
	if(_script[SelectedScenario] == NULL)
	{
		StatusList.AddMessage("ERROR:System error :: script selection was losed");
		StatusList.AddMessage("ERROR:Close edit window and repeat last action");
		UpdateAllViews(0);
		return -1;
	}
	_script[SelectedScenario]->UpDateScriptFromTempList(&templist);
	UpdateAllViews(0);
	return 0;
}

void ZWaveeditorDoc::OnChangedViewList() 
{
	// TODO: Add your specialized code here and/or call the base class
	CDocument::OnChangedViewList();
	UpdateAllViews(0);
}

void ZWaveeditorDoc::OnAlwaysShowHint()
{
	bEnableGraphViewAlwaysShowHint = !bEnableGraphViewAlwaysShowHint;
	ptrGraphViewHint->SetDelayTime( TTDT_INITIAL, ( bEnableGraphViewAlwaysShowHint ? 1 : 1000 ) ); 
}

int ZWaveeditorDoc::OnEditscriptSave(CEdit *_myedit, int SelectedScenario)
{
	StatusList.ClearLog();
	int numoflines	=	_myedit->GetLineCount();
	if(numoflines <= 1)
	{
		StatusList.AddMessage("ERROR:No data to save :: Please input legal text");
		UpdateAllViews(0);
		return -1;
	}
	templist.ClearLog();

	FillTempListWithDataFromEditFrame( numoflines, _myedit);

//------------------- Global Values In Editing ----------------	
	if(SelectedScenario	==	-1)
	{
		OnEditSaveGlobalValues(&templist);
		return 0;		
	}
//-------------------------------------------------------------------------
	if(_script[SelectedScenario] == NULL)
	{
		StatusList.AddMessage("ERROR:System error :: script selection was losed");
		StatusList.AddMessage("ERROR:Close edit window and repeat last action");
		UpdateAllViews(0);
		return -1;
	}
	_script[SelectedScenario]->UpDateScriptFromTempList		(&templist);
	_script[SelectedScenario]->UpDateScriptFileFromTempList	(&templist);
	
	scenario	*newscenario	=	_script[SelectedScenario];
	CString		filename		=	newscenario->GetFileName();
	_script.RemoveAt(SelectedScenario);
	delete		newscenario	;
	newscenario	=	new scenario( &StatusList, filename );
	newscenario->LoadGlobalSignalListFromScriptFile( filename );
	int res	=	newscenario->LoadScriptFile(filename);
	_script.InsertAt(SelectedScenario,newscenario);

	treewaschanged	=	TRUE;
	UpdateAllViews(0);
	SetModifiedFlag(FALSE);
	OnEditscriptfile(last_tree,last_item);
	return 0;

}

void ZWaveeditorDoc::FillTempListWithDataFromEditFrame( int numoflines, CEdit *_myedit)
{
	char	_line[1025];
	CString FullLine,TempLine;
	int res;
	for(int i=0;i<numoflines;i++)
	{
		res = _myedit->GetLine(i,_line,1024);
		_line[res]	=	'\0';
		FullLine = _line;
		while ( res == 1024 )
		{
			i++;
			res = _myedit->GetLine(i,_line,1024);
            _line[res]	=	'\0';
			TempLine = _line;
			TempLine.MakeLower();
			if ( TempLine.Find("signal") >= 0 || TempLine.Find( "end" ) >= 0 )
			{
				templist.AddMessage( FullLine );
				FullLine = _line;
				break;
			}
			FullLine += _line;
		}
		templist.AddMessage( FullLine );
	}
}

void ZWaveeditorDoc::OnDeleteselectedscript(HTREEITEM pos)
{
	if((CheckIfEditWindowOpened() == TRUE)||(CheckIfGraphWindowOpened() == TRUE))
	{
		AfxMessageBox("Please Close All Graph and Editing Windows");
		return;
	}
	StatusList.ClearLog();
	for(int i=0;i<_script.GetSize();i++)
	{
		if(_script[i]->CheckIfSelectedScriptRoot(pos) == TRUE)
		{
			selectedscenario = ( i == _script.GetUpperBound() )? i-1:i;
			CString filename			=	_script[i]->GetFileName();
			scenario	*selscenrio		=	_script[i];
			_script.RemoveAt(i);
			delete		selscenrio;
			treewaschanged	=	TRUE;
			UpdateAllViews(0);
			return;
		}
	}
	StatusList.AddMessage("ERROR:Not found script to delete");
	UpdateAllViews(0);

}


int ZWaveeditorDoc::OnSavealltovectorfile()
{
	if((CheckIfEditWindowOpened() == TRUE)||(CheckIfGraphWindowOpened() == TRUE)||(_script.GetSize() <1))
	{
		AfxMessageBox("Please Close All Graph and Editing Windows and Check For Scripts");
		return -1;
	}
	StatusList.ClearLog();
	ZWaveeditorApp	*pWinapp	=	(ZWaveeditorApp*) AfxGetApp();
	CString			outputdir		=	pWinapp->OutputDirectory	+"\\";
	CString			vectorfilename	=	outputdir+"default.bin";
//-------------------------------------------------------------------------------------------
	char Filters[]= "Bin Files (*.bin)|*.bin|All Files (*.*)|*.*||";
	CFileDialog file(FALSE,"bin",vectorfilename,OFN_FILEMUSTEXIST| OFN_HIDEREADONLY, Filters);
	if (file.DoModal() == IDCANCEL)	
	{
		return -1;
	}
//--------------------------------------------------------------------------------------------
	vectorfilename	=	file.GetPathName();
	CString vectorfilenameonly	=	vectorfilename;
	int	pos			=	vectorfilename.Find(".bin",0);
	if(pos	>=	0)
	{
		vectorfilenameonly	=	vectorfilename.Mid(0,pos);
	}
	_script[0]->OpendialogWritingVector();
	filestocompress.ClearLog();
	fheaders.RemoveAll();
	PrepearBinFileHeader();
	int i=0;
	for(;i<_script.GetSize();i++)
	{
		if(_script[i]->OnSavealltovectorfile(outputdir,&filestocompress) == -1)
		{
			_script[i]->ClosedialogWritingVector();
			StatusList.AddMessage("ERROR:Error in script >"+_script[i]->GetFileName()+">");
			UpdateAllViews(0);
			return -1;
		}
	}
	_script[i-1]->ClosedialogWritingVector();
	number_of_information_raws_in_frame	=	7;
	if(PrepaireNewBinFile(vectorfilename)	==	-1)
	{ 
		StatusList.AddMessage("ERROR:Hardware error cannont write to disk");
		UpdateAllViews(0);
		return -1;
	}
	MultiRunCompressor(vectorfilenameonly);
	FinilizeBinFile(vectorfilename);

	UpdateAllViews(0);
	return 0;
}

void ZWaveeditorDoc::SetGraphVeiwHintState( bool NewState )
{
	bEnableGraphViewAlwaysShowHint = NewState;
}

bool ZWaveeditorDoc::GetGraphViewHintState()const
{
	return bEnableGraphViewAlwaysShowHint;
}

BOOL ZWaveeditorDoc::CheckIfEditWindowOpened()
{
	return EditWindowOpened;
}
BOOL ZWaveeditorDoc::CheckIfGraphWindowOpened()
{
	return GraphWindowOpened;
}


int ZWaveeditorDoc::OnGraphViewFromTree(CTreeCtrl *_tree, HTREEITEM _item)
{
	StatusList.ClearLog();
	for(int i=0;i<_script.GetSize();i++)
	{
		if(_script[i]->CheckIfSelectedGroup(_tree,_item) == TRUE)
		{
			selectedscenario = i;
			_script[i]->globalsignals->RefreshSignalsStatus();
	//---------------------------------------------------------------------------------------			
			CString name				=	_tree->GetItemText(_item);
			int posbegin				=	name.Find("<",0);
			int posend					=	name.Find(">",0);
			GroupName					=	name.Mid(posbegin+1,posend-posbegin-1);
	//----------------------------------------------------------------------------------------
			return OnGraphView( selectedscenario, GroupName );
		}
	}
	StatusList.AddMessage("ERROR:Not found group to show in graph");
	UpdateAllViews(0);
	return -1;
}

int ZWaveeditorDoc::OnGraphView( int SelectedScenarioNumber, CString GroupName )
{
	int Result = -1;
	CloseGraphWindow();
	CloseEditWindow();
	if ( _script[SelectedScenarioNumber]->SetGraphDataTotalSize( &(_script[SelectedScenarioNumber]->mygraphdata), GroupName ) == 0 )
	{
		graphframe = ((ParentMainFrame *) AfxGetMainWnd())->onGraphWindow();
		if ( _script[SelectedScenarioNumber]->FirstInitGraphData( &(_script[SelectedScenarioNumber]->mygraphdata),
																  GroupName, 
																  0, 
																  _script[SelectedScenarioNumber]->mygraphdata.GetTotalSize(), 
																  graphwindowMaxX ) == 0 )
		{
			StatusList.AddMessage("Graph view frame <"+GroupName+"> was generated successfuly");
			SetGraphWindowOpened();
			Result = 0;
		}
		else
		{
			graphframe->DestroyWindow();
		}
	}
	UpdateAllViews(0);
	return Result;
}

void ZWaveeditorDoc::CloseEditWindow()
{
	if ( CheckIfEditWindowOpened() == TRUE )
	{
		editframe->DestroyWindow();
		SetEditWindowClosed();
	}
}

void ZWaveeditorDoc::SetGraphViewHintPointer( CToolTipCtrl* ptrToolTip )
{
	ptrGraphViewHint = ptrToolTip;
}

void ZWaveeditorDoc::SetDispStatusBar0Value( int StartNum1, int StartNum2, int StartNum3)
{
	ParentMainFrame* pFrame			   = (ParentMainFrame*) AfxGetMainWnd();
	pFrame->m_wndStatusBar.StartNum[0] = StartNum1;
	pFrame->m_wndStatusBar.StartNum[1] = StartNum2;
	pFrame->m_wndStatusBar.StartNum[2] = StartNum3;
}

void ZWaveeditorDoc::SetGraphStatusBarText( CArray<CString> *Texts, CArray<int> *Colors, CArray<int> *Sizes, int StatusBarIndex )
{
	ParentMainFrame*		pFrame		=	(ParentMainFrame*) AfxGetMainWnd();

	CStatusBarCtrl*			StatusBarControl;
	myStatusBar*			StatusBar;
	switch ( StatusBarIndex )
	{
		case 0:
			{
				StatusBarControl = &pFrame->m_wndStatusBar.GetStatusBarCtrl();
				StatusBar		 = &pFrame->m_wndStatusBar;
			}break;
		case 1:
			{
				StatusBarControl	=	&pFrame->m_wndStatusBar2.GetStatusBarCtrl();
				StatusBar			=	&pFrame->m_wndStatusBar2;
			}break;
		default: return;
		}

	StatusBar->DestroyAllText();
	UINT			nID;
	UINT			nStyle;
	int				cxWidth;
	
	for ( int i = 0; i < Texts->GetCount(); i++ )
	{
		CString tmpText = (*Texts)[i];	
		StatusBar->AddItemText( tmpText, (Colors->GetCount()>i) ? (*Colors)[i] : RGB(0,0,0) );
		StatusBar->GetPaneInfo( i+1, nID, nStyle, cxWidth);
		StatusBar->SetPaneInfo( i+1, nID, nStyle, (Sizes->GetCount()>i) ? (*Sizes)[i] : 150 );
		StatusBarControl->SetText( tmpText, i+1, SBT_OWNERDRAW);
	}
}

void ZWaveeditorDoc::OnDocumentproperties() 
{
	// TODO: Add your command handler code here
	PropertiesDialog.compressionstep	=	compressionstep;
	PropertiesDialog.efectiveedge		=	efectiveedge;	
	PropertiesDialog.twopath			=	twopath;
	PropertiesDialog.DoModal();
	compressionstep	=	PropertiesDialog.compressionstep;
	efectiveedge	=	PropertiesDialog.efectiveedge;
	twopath			=	PropertiesDialog.twopath;
}


void ZWaveeditorDoc::MultiRunCompressor(CString outputname)
{
/**/FILE *batFile ;
	batFile	=	fopen("command.bat","w");
	if(batFile	!=	NULL)
	{
		ZWaveeditorApp	*pWinapp=	(ZWaveeditorApp*) AfxGetApp();
		CString			root	=	'"'+pWinapp->ConfigurationDirectory+"\\utg_compressor.exe"+'"'+" -waveeditor ";
		if(efectiveedge == 1)
		{
			root +=	" -ee 1 ";
		}
		else
		{
			root +=	" -ee 0 ";
		}
		if(twopath	==	BST_CHECKED)
		{
			root += " -two_pass ";
		}
		CString param[8];
		param[0]	=	" -htotal "; 
		param[1]	=	" -vtotal "; 
		param[2]	=	" -compressor ";
		for(int i=0;i<filestocompress.GetNumberOfMessages()/number_of_information_raws_in_frame;i++)
		{
			StatusList.AddMessage("file"+filestocompress.GetMessage(i*number_of_information_raws_in_frame)+" was generated successfuly");
			CString commandname;
			commandname			=	root+" -input "+filestocompress.GetMessage(i*number_of_information_raws_in_frame);
			for(int ii=0;ii<2;ii++)
			{
				if(filestocompress.GetMessage(i*number_of_information_raws_in_frame+2+ii) != "")
				{
					commandname	=commandname + param[ii] + filestocompress.GetMessage(i*number_of_information_raws_in_frame+2+ii);
				}
			}
			commandname	=	commandname+" -output "+'"'+outputname+'"';
			

			if(compressionstep	==	STEPB)
			{
				commandname +=" -stepB ";
				if(filestocompress.GetMessage(i*number_of_information_raws_in_frame+5) != "")
				{
					commandname	+=	" -load_req "+filestocompress.GetMessage(i*number_of_information_raws_in_frame+5)+" -fine_res "+filestocompress.GetMessage(i*number_of_information_raws_in_frame+5);
				}
				if(filestocompress.GetMessage(i*number_of_information_raws_in_frame+6)	!=	"")
				{
					commandname	+=	" -reset_sub "+ filestocompress.GetMessage(i*number_of_information_raws_in_frame+6);
				}
			}
			else
			{
				commandname	+=" -stepA ";
			}
			CString specialadd =filestocompress.GetMessage(i*number_of_information_raws_in_frame+2+2);
			CString s1='"';
			specialadd.Replace(s1," ");
			commandname	=commandname + " -stat " +specialadd ;
			commandname		+=	" >> "+pWinapp->OutputDirectory+"\\logfile.txt "+"\n";
			fwrite(LPCTSTR(commandname),commandname.GetLength(),1,batFile);
		}
		fclose(batFile);
		do{		
			batFile	=	fopen("command.bat","r");
		}while(batFile	== NULL);
		fclose(batFile);
		SHELLEXECUTEINFO sei	= {0};
		sei.cbSize				= sizeof sei;
		sei.lpVerb				= "open";
		sei.lpFile				= "command.bat";
		sei.nShow				= SW_HIDE;
		sei.fMask				= SEE_MASK_NOCLOSEPROCESS ;
		ShellExecuteEx(&sei);
		WaitForSingleObjectEx(sei.hProcess,2000,TRUE);
		CloseHandle(sei.hProcess);
		
	}
}

void ZWaveeditorDoc::RunCompressor(CString inputfile, CString outputfile, CString HTotal, CString VTotal,CString VTotal_2,CString SubRes)
{
/**/FILE *batFile ;
	batFile	=	fopen("command.bat","w");
	if(batFile	!=	NULL)
	{
		ZWaveeditorApp	*pWinapp	=	(ZWaveeditorApp*) AfxGetApp();
		CString commandname;
		CString			root	=	'"'+pWinapp->ConfigurationDirectory+"\\utg_compressor.exe"+'"'+" -waveeditor ";
		if(efectiveedge == 1)
		{
			root +=	" -ee 1 ";
		}
		else
		{
			root +=	" -ee 0 ";
		}
		if(twopath	==	BST_CHECKED)
		{
			root += " -two_pass ";
		}
		

		if((HTotal != "")&&(VTotal != ""))
		{
			commandname			=	root +" -input "+ inputfile+" -htotal "+HTotal+" -vtotal "+VTotal+" -output "+'"'+
									outputfile+'"';//+compression_step_string[compressionstep];

		}
		else
		{
			commandname			=	root +" -input "+	inputfile+" -output "+"'"+outputfile+'"';//+compression_step_string[compressionstep];
		}

		if(compressionstep	==	STEPB)
		{
			commandname	+=	" -stepB ";
			if(VTotal_2 != "")
			{
				commandname	+=	" -load_req "+VTotal_2+" -fine_res "+VTotal_2;
			}
			if(SubRes	!=	"")
			{
				commandname	+=	" -reset_sub "+ SubRes;
			}
		}
		else
		{
			commandname	+=" -stepA";
		}
		commandname		+=	" -stat >> "+pWinapp->OutputDirectory+"\\logfile.txt \n";
		fwrite(LPCTSTR(commandname),commandname.GetLength(),1,batFile);
		fclose(batFile);
		do{		
			batFile	=	fopen("command.bat","r");
		}while(batFile	== NULL);
		fclose(batFile);
		SHELLEXECUTEINFO sei	= {0};
		sei.cbSize				= sizeof sei;
		sei.lpVerb				= "open";
		sei.lpFile				= "command.bat";
		sei.nShow				= SW_HIDE;
		sei.fMask				= SEE_MASK_NOCLOSEPROCESS ;
		ShellExecuteEx(&sei);
		WaitForSingleObjectEx(sei.hProcess,2000,TRUE);
		CloseHandle(sei.hProcess);
		
	}
}


int ZWaveeditorDoc::PrepaireNewBinFile(CString filename)
{
	FILE	*pVfile	=	fopen(filename,"wb");	
	if(pVfile	==	NULL)
	{
		return -1;
	}
	bin_fileheader.waveeditorversion		=	(3<<24)+(2<<16)+(3<<8)+1;
	if(compressionstep	==	STEPB)
	{
		bin_fileheader.chipversion				=	STEPBNUM;
	}
	else
	{
		bin_fileheader.chipversion				=	STEPANUM;
	}
	bin_fileheader.NumberOffFramesInBinFile	=	filestocompress.GetNumberOfMessages()/number_of_information_raws_in_frame;
	DWORD	hsize	=	sizeof(struct binfileheader);
	char   nm[20];
	_itoa(hsize,nm,10);
	CString snum = nm ;
//	AfxMessageBox("Size of struct ="+snum);
	fwrite(&hsize,sizeof(DWORD),1,pVfile);
	fwrite(&bin_fileheader,sizeof(struct binfileheader),1,pVfile);
	for(unsigned int i=0;i<bin_fileheader.NumberOffFramesInBinFile;i++)
	{
		frameheader			newfh;
		newfh.FrameID		=	(DWORD)atol(LPCTSTR (filestocompress.GetMessage(i*number_of_information_raws_in_frame+1)));
		newfh.HTotal		=	(DWORD)atol(LPCTSTR (filestocompress.GetMessage(i*number_of_information_raws_in_frame+2)));
		newfh.VTotal		=	(DWORD)atol(LPCTSTR (filestocompress.GetMessage(i*number_of_information_raws_in_frame+3)));
		newfh.NFS			=	(DWORD)atol(LPCTSTR (filestocompress.GetMessage(i*number_of_information_raws_in_frame+6)));
		newfh.OffSetToCode	=	0;
		newfh.Size			=	0;
//		newfh.EXTRA[0]		=	0;
//		newfh.EXTRA[1]		=	0;
//		newfh.EXTRA[2]		=	0;
		fwrite(&newfh,sizeof(struct frameheader),1,pVfile);
		fheaders.Add(newfh);
	}
	fclose(pVfile);
	return 0;
}

void ZWaveeditorDoc::FinilizeBinFile(CString filename)
{
	StatusList.ClearLog();
	FILE	*pVfile=NULL;
	while(pVfile == NULL)
	{
		pVfile	=	fopen(filename,"r+b");	
	}
	StatusList.AddMessage("file - "+filename+" was opened for rebuilding");
	if(pVfile	==	NULL)
	{
		return ;
	}
	int res	=	fseek(pVfile,0,SEEK_SET);
	if(res!=0)
	{
		StatusList.AddMessage("ERROR:file - "+filename+" seek operation not worked");
	}
	DWORD	offset;
	DWORD   htotal;
	DWORD   vtotal;
	DWORD	size;
	DWORD	hsize;
	fread(&hsize,sizeof(DWORD),1,pVfile);
	fread(&bin_fileheader,hsize,1,pVfile);
	char sz[20];
	itoa(bin_fileheader.NumberOffFramesInBinFile,sz,10);
	StatusList.AddMessage("Number of frames in file is -"+CString(sz));
	offset =	sizeof(DWORD)+sizeof(struct binfileheader)+bin_fileheader.NumberOffFramesInBinFile*sizeof(struct frameheader);//+sizeof(BYTE);
	for(unsigned int i=0;i<bin_fileheader.NumberOffFramesInBinFile;i++)
	{
//-------------------------------------------------------------------
		fseek(pVfile,offset,SEEK_SET);
//-------------------------------------------------------------------
		fread(&htotal	,sizeof(DWORD),1,pVfile);
		offset	+=sizeof(DWORD);
//-------------------------------------------------------------------
		fseek(pVfile,offset,SEEK_SET);
//-------------------------------------------------------------------
		fread(&vtotal	,sizeof(DWORD),1,pVfile);
		offset	+=sizeof(DWORD);
//-------------------------------------------------------------------
		fseek(pVfile,offset,SEEK_SET);
//-------------------------------------------------------------------
		fread(&size	,sizeof(DWORD),1,pVfile);
		offset	+=sizeof(DWORD);
//-------------------------------------------------------------------
		fheaders[i].OffSetToCode	=	offset;
		offset	+=size;
		fheaders[i].Size			=	size;
		strcpy(sz,"");itoa(size,sz,10);
		StatusList.AddMessage("Size off Frame number ["+filestocompress.GetMessage(i*number_of_information_raws_in_frame+1)+"] is "+sz+" bytes");

	}
	offset	=	sizeof(DWORD)+sizeof(struct binfileheader);
	for(unsigned int i=0;i<bin_fileheader.NumberOffFramesInBinFile;i++)
	{
		fseek(pVfile,offset,SEEK_SET);
		fwrite(&fheaders[i],sizeof(struct frameheader),1,pVfile);
		offset +=	sizeof(struct frameheader);
	}
	fclose(pVfile);
	UpdateAllViews(0);
}

void ZWaveeditorDoc::OnEditGlobalValues(mymessages* templist)
{
	CString line		=	"PHASE GLOBAL =";
	CString		endline	=	"\r\r\n";
	line	+=" "+GetStringFromNumber(doc_fileheader.global_phase)+endline;
	templist->ClearLog();
	templist->AddMessage(line);
//-------------------  RISE FALL signals	
	line = ";-------------------- PHASE  SIGNAL RISE/FALL		"+endline;
	templist->AddMessage(line);
	for(int i=0;i<NUMBEROFPHASEDRIVE;i++)
	{
			line		=	"PHASE "+phase_drive_names[i]+" RISE = ";
			line		+=	GetStringFromNumber(doc_fileheader.rise[i])+ " FALL = ";
			line		+=	GetStringFromNumber(doc_fileheader.fall[i])+endline;
			templist->AddMessage(line);
	}
//-------------------- DRIVE signal	
	line = ";-------------------- DRIVE SIGNAL		----------------"+endline;
	templist->AddMessage(line);

	for(int i=0;i<NUMBEROFPHASEDRIVE;i++)
	{
			line		=	"DRIVE "+phase_drive_names[i]+" = ";
			line		+=	GetStringFromNumber(doc_fileheader.drive[i])+endline;
			templist->AddMessage(line);
	}
}

CString ZWaveeditorDoc::rebuild_string_to_command(CString _line)
{
	int pos = _line.Find("//",0);
	if(pos>-1)
	{
		_line	=	_line.Mid(0,pos);
	}
	pos = _line.Find(";",0);
	if(pos>-1)
	{
		_line	=	_line.Mid(0,pos);
	}
	_line.MakeLower();
	_line.Replace('\t',' ');
	_line.TrimLeft();//" ");
	for(int i=1;i<_line.GetLength();i++)
	{
		if(((_line[i-1] == ' ')||(_line[i-1] == '\t'))&&((_line[i] == ' ')||(_line[i] == '\t')))
		{
			_line.SetAt(i,'\t');
		}
	}

	_line.Remove('\t');
	_line.Remove('\n');
	_line.Remove('\r');
	return _line;
}


void ZWaveeditorDoc::OnEditSaveGlobalValues(mymessages* templist)
{
	int linecount	=	templist->GetNumberOfMessages();
	for(int i=0;i<linecount;i++)
	{
		CString command	=	rebuild_string_to_command(templist->GetMessage(i));
		CheckIfGlobalPhase(command);
		CheckIfPhase(command);
		CheckIfDrive(command);
	}
}

int ZWaveeditorDoc::CheckIfGlobalPhase(CString scriptline)
{
	if(scriptline.Find("phase global")	<	0)
	{
		return -1;
	}
	int p[5];
	CString		param;
	CString		pparam;
	param	=	"global";
	for(int i=0;i<1;i++)
	{
		p[0]			=	scriptline.Find(param,0);
		if(p[0] >0)
		{
			p[1]			=	scriptline.Find('=',p[0]);
			p[2]			=	scriptline.Find(' ',p[1]);
			if(p[2]<0)
			{
				pparam		=	scriptline.Mid(p[1]+1);
			}
			else
			{
				if((p[2]-p[1]) == 1)
				{
					p[1]			=	p[2];
					p[2]			=	scriptline.Find(' ',p[1]+1);
				}
				if(p[2]<0)
				{
					pparam		=	scriptline.Mid(p[1]+1);
				}
				else
				{
					pparam		=	scriptline.Mid(p[1]+1,p[2]-p[1]-1);
				}
			}
			doc_fileheader.global_phase	=	GetNumberFromString(pparam);
		}
	}
	return 0;
}




int ZWaveeditorDoc::CheckIfPhase(CString scriptline)
{
	int pos	=	-1;
	if(scriptline.Find("phase")	<	0)
	{
		return -1;
	}
	CString res;
	int i=0;
	for(;i<NUMBEROFPHASEDRIVE;i++)
	{
		res	=	" "+rebuild_string_to_command(" "+phase_drive_names[i])+" ";
		if(scriptline.Find(res) >= 0)
		{
			pos	=	i;
			i	=	NUMBEROFPHASEDRIVE;
		}

	}
	if(pos	<	0)
	{
		return -1;
	}
	int p[5];
	CString		pparam;//[NUMBEROFPHASEDRIVE]
	CString		param[2];//[NUMBEROFPHASEDRIVE]
	param[0]	=	"rise";
	param[1]	=	"fall";
	for(i=0;i<2;i++)
	{
		p[0]			=	scriptline.Find(param[i],0);
		if(p[0] >0)
		{
			p[1]			=	scriptline.Find('=',p[0]);
			p[2]			=	scriptline.Find(' ',p[1]);
			if(p[2]<0)
			{
				pparam		=	scriptline.Mid(p[1]+1);
			}
			else
			{
				if((p[2]-p[1]) == 1)
				{
					p[1]			=	p[2];
					p[2]			=	scriptline.Find(' ',p[1]+1);
				}
				if(p[2]<0)
				{
					pparam		=	scriptline.Mid(p[1]+1);
				}
				else
				{
					pparam		=	scriptline.Mid(p[1]+1,p[2]-p[1]-1);
				}
			}
			if(i	==	0)
			{
				doc_fileheader.rise[pos]	=	GetNumberFromString(pparam);
			}
			else
			{
				doc_fileheader.fall[pos]	=	GetNumberFromString(pparam);
			}
		}
	}
	
	return 0;
}





int ZWaveeditorDoc::CheckIfDrive(CString scriptline)
{
	if(scriptline.Find("drive")	<	0)
	{
		return -1;
	}
	int pos	=	-1;
	int p[5];
	CString		pparam;
	CString		param[2];
	CString		res;
	int i=0;
	for(;i<NUMBEROFPHASEDRIVE;i++)
	{
		res	=	" "+rebuild_string_to_command(phase_drive_names[i]);
		if(scriptline.Find(res) >= 0)
			
		{
			pos	=	i;
			i	=	NUMBEROFPHASEDRIVE;
			param[0]	=	res;
		}

	}
	if(pos	<	0)
	{
		return -1;
	}
	for(i=0;i<1;i++)
	{
		p[0]			=	scriptline.Find(param[i],0);
		if(p[0] >0)
		{
			p[1]			=	scriptline.Find('=',p[0]);
			p[2]			=	scriptline.Find(' ',p[1]);
			if(p[2]<0)
			{
				pparam		=	scriptline.Mid(p[1]+1);
			}
			else
			{
				if((p[2]-p[1]) == 1)
				{
					p[1]			=	p[2];
					p[2]			=	scriptline.Find(' ',p[1]+1);
				}
				if(p[2]<0)
				{
					pparam		=	scriptline.Mid(p[1]+1);
				}
				else
				{
					pparam		=	scriptline.Mid(p[1]+1,p[2]-p[1]-1);
				}
			}
			doc_fileheader.drive[pos]	=	GetNumberFromString(pparam);
		}
	}
	
	return 0;
}


int ZWaveeditorDoc::GetNumberFromString(CString snumber)
{
	CString left,right;
	int sgn	=	1;
	int pos	=	snumber.Find("-");
	if(pos>=0)
	{
		sgn		=	-1;
	}
	pos		=	snumber.Find(".");
	if(pos >0)
	{
		left	=	snumber.Mid(0,pos);
		right	=	snumber.Mid(pos+1);
	}
	else
	{
		left	=	snumber;
		right	=	"";
	}
	int lft	=	abs(atoi(left));
	if(right.GetLength()<2)
	{
		right +="0";
	}
	else
	{
		right.Delete(2,right.GetLength());
	}

	int	rgt	=	abs(atoi(right));
	lft	=	(lft*100+rgt)*sgn;

	return lft;
}

CString ZWaveeditorDoc::GetStringFromNumber(int number)
{
	BOOL signneg	=	FALSE;
	if(number < 0)
	{
		signneg	=	TRUE;
	}
	number				=	abs(number);
	int		beforedot	=	number / 100;
	int		afterdot	=	number % 100;
	char    chnum1[10];
	char	chnum2[10];
	_itoa(beforedot,chnum1,10);
	CString snum	=	chnum1;
	if(afterdot	!= 0)
	{
		_itoa(afterdot,chnum2,10);
		snum =snum+"."+chnum2;
	}
	CString res;
	if(signneg	==	TRUE)
	{
		res	="-"+snum;
	}
	else
	{
		res	=	snum;
	}
	return res;
}

int ZWaveeditorDoc::BinFileHeaderSerialize(CArchive& ar)
{
	if (ar.IsStoring())
	{
		// TODO: add loading code here
		ar<<doc_fileheader.waveeditorversion;
		ar<<doc_fileheader.NumberOffFramesInBinFile;
		ar<<doc_fileheader.chipversion;
		ar<<doc_fileheader.global_phase;
		ar<<doc_fileheader.number_of_signals;
		for(int i=0;i<doc_fileheader.number_of_signals;i++)
		{
			ar<<doc_fileheader.rise[i];
			ar<<doc_fileheader.fall[i];
			ar<<doc_fileheader.drive[i];
		}
	}
	else
	{
		ar>>doc_fileheader.waveeditorversion;
		ar>>doc_fileheader.NumberOffFramesInBinFile;
		ar>>doc_fileheader.chipversion;
		ar>>doc_fileheader.global_phase;
		ar>>doc_fileheader.number_of_signals;
		for(int i=0;i<doc_fileheader.number_of_signals;i++)
		{
			ar>>doc_fileheader.rise[i];
			ar>>doc_fileheader.fall[i];
			ar>>doc_fileheader.drive[i];
		}
	}
	return 0;
}

void ZWaveeditorDoc::PrepearBinFileHeader(void)
{
	bin_fileheader.chipversion				=	doc_fileheader.chipversion;
	bin_fileheader.NumberOffFramesInBinFile =	doc_fileheader.NumberOffFramesInBinFile;
	bin_fileheader.waveeditorversion		=	doc_fileheader.waveeditorversion;
	bin_fileheader.number_of_signals		=	doc_fileheader.number_of_signals;
	bin_fileheader.global_phase				=	ROUND((doc_fileheader.global_phase*4)/100);
	for(int i=0;i<bin_fileheader.number_of_signals;i++)
	{
		bin_fileheader.rise	[i]				=	ROUND((doc_fileheader.rise	[i]*4)/100);
		bin_fileheader.fall	[i]				=	ROUND((doc_fileheader.fall	[i]*4)/100);
		bin_fileheader.drive[i]				=	ROUND((doc_fileheader.drive	[i]*4)/100);
	}
}

void ZWaveeditorDoc::OnReloadLogWithChosenProperties( int NumberOfScenario )
{
	scenario *OldScenario = _script[NumberOfScenario];
	ReadingModeDialog RMD( OldScenario->LogReadType );
	int Result = RMD.DoModal();
	if ( Result == IDCANCEL )
	{
		return;
	}
	LogReadingType ReadType = RMD.GetReadType();
	CArray< Signal, Signal > Signals;
	unsigned __int64 TotalSize = 0;
	if ( !GetValuesFromLogFile( OldScenario->filename, &Signals, TotalSize, ReadType ) )
	{
		return;
	}
	if ( Result != ID_GET_ALL )
	{
		ExcludeUnnecessarySignals( Signals, ReadType, OldScenario );
	}
	ConvertOldSignalValuesToScriptCompatible( Signals );

	scenario	*NewScenario	=	new scenario(&StatusList, OldScenario->filename );
	NewScenario->LogReadType = ReadType;
	NewScenario->FreeSpaceCutOff = !OldScenario->FreeSpaceCutOff;
	NewScenario->TimeDivider = OldScenario->TimeDivider;
	NewScenario->LoadGlobalSignalListFromArray( Signals );
	NewScenario->LoadSignalsFromArray( Signals, TotalSize );
	_script.SetAt( NumberOfScenario, NewScenario );
	NewScenario->CutReturnFreeSpace();
	OnGraphView( NumberOfScenario, OldScenario->mygraphdata.GetGroupName() );
	selectedscenario = NumberOfScenario;
	treewaschanged	=	TRUE;
	StatusList.AddMessage("Loading file : '"+NewScenario->filename+"'  Succeded");
	delete OldScenario;
}

void ZWaveeditorDoc::ExcludeUnnecessarySignals( CArray< Signal, Signal > &Signals, LogReadingType ReadType, scenario *OldScenario )
{
	long (LogReadingType::*TypeOfChosenLines) = &LogReadingType::TypeOfBracketLines;
	ExcludeUnnecessarySignalsForChosenType( Signals, ReadType, TypeOfChosenLines, SIGNAL_WITH_TRIANGULAR_BRACKETS, OldScenario );
	ExcludeUnnecessarySignalsForChosenType( Signals, ReadType, TypeOfChosenLines, SIGNAL_WITH_SQUARE_BRACKETS, OldScenario );
	TypeOfChosenLines = &LogReadingType::TypeOfNoBracketLines;
	ExcludeUnnecessarySignalsForChosenType( Signals, ReadType, TypeOfChosenLines, SIGNAL_WITHOUT_BRACKETS, OldScenario );
}

void ZWaveeditorDoc::ExcludeUnnecessarySignalsForChosenType( CArray< Signal, Signal > &Signals,
														    LogReadingType ReadType, 
															long (LogReadingType::*TypeOfChosenLines),
															long TypeOfLineInSignals,
															scenario *OldScenario )
{
	if ( ReadType.*TypeOfChosenLines == NO_READ )
	{
		for ( int i = 0; i < Signals.GetSize();)
		{
			if ( Signals[i].SignalType == TypeOfLineInSignals )
			{
				Signals.RemoveAt( i );
			}
			else
			{
				i++;
			}
		}
	}
	else if ( ReadType.*TypeOfChosenLines == OldScenario->LogReadType.*TypeOfChosenLines )
	{
		OldScenario->ExcludeUnusedStringsByPreciseName( Signals, TypeOfLineInSignals );
	}
	else if ( ReadType.*TypeOfChosenLines == BY_WORD && OldScenario->LogReadType.*TypeOfChosenLines == BY_STRING )
	{
		OldScenario->ExcludeChangesByString( Signals, TypeOfLineInSignals );
	}
	else if ( ReadType.*TypeOfChosenLines == BY_STRING && OldScenario->LogReadType.*TypeOfChosenLines == BY_WORD )
	{
		OldScenario->ExcludeUnusedStringsByWord( Signals, TypeOfLineInSignals );
	}
}

CString ZWaveeditorDoc::CreateSRPFile( CString OldFileName, const CArray< Signal, Signal > &Signals, long TotalSize )
{
	OldFileName = OldFileName.Mid( 0, OldFileName.ReverseFind( '.' ) + 1 );
	OldFileName += "srp.tmp";
	CStdioFile TemporarySRP;
	TemporarySRP.Open( OldFileName, CFile::modeCreate | CFile::modeWrite );
	FillTemporaryFiles( Signals, &TemporarySRP, TotalSize );
	TemporarySRP.Close();
	return OldFileName;
}

void ZWaveeditorDoc::FillTemporaryFiles( const CArray< Signal, Signal > &Signals,
					CStdioFile * TemporarySRP,
					long TotalSize )
{
	long NumberOfSignals = Signals.GetCount();
	if ( NumberOfSignals == 0 )
	{
		return;
	}
	TemporarySRP->WriteString( "GROUP TIMING \"Timing\" " + Long64ToCString(TotalSize) + (( Signals[0].TimeType == MILLI_SECONDS ) ? " ms" : " us") + "\r\n" );
	for ( int i = 0; i < NumberOfSignals; i++ )
	{
			CString SignalString = "\r\n\tSIGNAL " + Signals[i].Name + " = PWM "+Long64ToCString(Signals[i].FirstStatus) + " -1";
			long NumberOfChanges = Signals[i].Changes.GetCount();
			for ( int j = 0; j < NumberOfChanges; j++ )
			{
				SignalString +=" "+Long64ToCString(Signals[i].Changes[j]);
			}
			TemporarySRP->WriteString( SignalString );
	}
	TemporarySRP->WriteString( "\r\n\nGROUP_END\r\n\n\n" );
	TemporarySRP->WriteString( "FRAME 1 \"timing\" htot="+Long64ToCString(TotalSize)+" vtot=1\r\n\n" );
	CString GroupString = "\t1*TIMING";
	GroupString += "\r\n\n";
	TemporarySRP->WriteString( GroupString );
	TemporarySRP->WriteString( "FRAME_END\r\n" );
}

void ZWaveeditorDoc::OnFileSave()
{
	if ( m_strPathName == "" )
	{
		ZWaveeditorApp	*pWinapp	=	(ZWaveeditorApp*) AfxGetApp();
		CString DocDir			=	pWinapp->DocumentDirectory;
		DocDir					+=	"\\*.sow";
		char Filters[]= "ZWaveEditorDocument Files (*.sow)|*.sow|All Files (*.*)|*.*||";
		CFileDialog FileDialog(FALSE,"sow",DocDir, NULL , Filters);
		if (FileDialog.DoModal() == IDOK)	
		{
			POSITION pos	=FileDialog.GetStartPosition();
			if(pos == NULL)
			{
				return;
			}
			m_strPathName = FileDialog.GetNextPathName(pos);
		}
		else
		{
			return;
		}
	}
	DoSave( m_strPathName );
	UpdateAllViews(0);
}

void ZWaveeditorDoc::OnFileSaveAs()
{
	CString OldPathName = m_strPathName;
	m_strPathName = "";
	OnFileSave();
	if ( m_strPathName == "" )
	{
		m_strPathName = OldPathName;
	}
}